package com.changy.ai_tutor_for_dm.service.impl;

import com.changy.ai_tutor_for_dm.context.UserContext;
import com.changy.ai_tutor_for_dm.entity.Classes;
import com.changy.ai_tutor_for_dm.mapper.ClassesMapper;
import com.changy.ai_tutor_for_dm.service.ClassesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class ClassesServiceImpl implements ClassesService {

    @Autowired
    private ClassesMapper classesMapper;

    /**
     * 生成8位随机数 2位字母加上6位数字
     */
    private static String generateRandomCode() {
        StringBuilder code = new StringBuilder();
        // 生成2位随机字母 (A-Z)
        for (int i = 0; i < 2; i++) {
            char letter = (char) ('A' + Math.random() * 26);
            code.append(letter);
        }
        // 生成6位随机数字
        for (int i = 0; i < 6; i++) {
            code.append((int) (Math.random() * 10));
        }
        return code.toString();
    }
    @Override
    public void createClass(Classes classes) {
        // 1. 设置teacherId
        classes.setTeacherId(UserContext.getCardId());
        // 2. 设置创建时间
        classes.setCreateTime(LocalDateTime.now());
        // 3. 生成随机且唯一的六位字符串accessCode， 插入数据库
        // 最多10次生成，数据库accesscode字段唯一，所以排除重复可能
        int maxRetries = 10;
        for (int i = 0; i < maxRetries; i++) {
            String accessCode = generateRandomCode();
            classes.setAccessCode(accessCode);
            try {
                classesMapper.insert(classes); // 尝试插入
                return; // 成功则直接返回
            } catch (DuplicateKeyException e) {
                // 捕获唯一键冲突异常，说明发生了碰撞
                log.warn("访问码 {} 已存在。正在重试... (尝试次数: {}/{})", accessCode, i + 1, maxRetries);
                // 循环继续，生成新的 accessCode 再试
            }
        }
    }

    @Override
    public List<Classes> getClasses(String cardId) {
        return classesMapper.getClassesByCardId(cardId);
    }

}
